﻿using Google.Apis.Calendar.v3.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace CalendarScreenSaver
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        GoogleCalendarManager _manager;
        public MainWindow()
        {
            InitializeComponent();            
            _manager = new GoogleCalendarManager();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            WindowStyle = System.Windows.WindowStyle.None;
            WindowState = System.Windows.WindowState.Maximized;

            Settings settings = SettingsManager.ReadSettings();
            if (settings == null)
            {
                MessageBox.Show("Please configure the screen saver before using it.", "Alert", MessageBoxButton.OK, MessageBoxImage.Information);
                Close();
            }

            tbUsername.Text = "Username: " + settings.UserName;
            tbCalendarName.Text = "Calendar: " + settings.CalendarName;
            var waiter = _manager.GetMyEventsAsync(settings);
            List<Event> events = waiter.Result;

            if (events != null)
            {
                foreach (var evt in events)
                {
                    WpfScheduler.Event ev = new WpfScheduler.Event
                    {
                        Start = evt.Start.DateTime.Value,
                        End = evt.End.DateTime.Value,
                        Subject = evt.Summary,
                        Description = evt.Description,
                        Color = Brushes.CornflowerBlue
                    };

                    wkScheduler.AddEvent(ev);
                }
            }
            else
            {
                MessageBox.Show(string.Format("There is no calendar named {0} in your list of calendars", settings.CalendarName), "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                Close();
            }
        }

        private void Window_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Escape)
            {
                Close();
            }
            else if (e.Key == Key.F1)
            {
                SettingsWindow win = new SettingsWindow();
                win.ShowDialog();
            }
        }

        private void Window_Activated(object sender, EventArgs e)
        {
        }
    }
}
